package com.deliveryservicesystem.presentation.desktop;

import com.deliveryservicesystem.app.exceptions.OutputError;
import com.deliveryservicesystem.app.util.AppFileLoc;
import com.deliveryservicesystem.app.util.AppUtils;
import com.deliveryservicesystem.dataaccess.DatabaseConnection;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.*;

/**
 * File Name: LoginDialog.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.presentation.desktop
 * Author: Lance
 * Date: Jun 30, 2012
 * Editor:
 */
public class LoginDialog extends javax.swing.JDialog
{

    public static final int RET_CANCEL = 0;
    public static final int RET_OK = 1;
    private static final long serialVersionUID = 1L;
    private String databasePropertiesFilePath;
    private boolean loginSuccess = false;
    private boolean initDatabase = true;

    public LoginDialog(java.awt.Frame parent, boolean modal)
    {
        super(parent, modal);
        initComponents();
        databasePropertiesFilePath = AppFileLoc.DATABASE_PROPERTIES_FILEPATH;
        setResizable(false);
        AppUtils.locateOnScreenCenter(this);
        setVisible(true);
        setTitle("Login");

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction()
        {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e)
            {
                doClose(RET_CANCEL);
            }
        });
    }

    public boolean getLoginSuccess()
    {
        return loginSuccess;
    }

    public boolean getInitDatabase()
    {
        return initDatabase;
    }

    public int getReturnStatus()
    {
        return returnStatus;
    }

    private void doLogin()
    {
        try
        {
            getDatabaseCredentials();
            testDatabaseCredentials();
            loginSuccess = true;
            initDatabase = ckbInitDb.isSelected();
        }
        catch (SQLException | IOException ex)
        {
            OutputError.toLog(ex);
            OutputError.toUser(ex);
        }
    }

    @SuppressWarnings("deprecation")
    private void getDatabaseCredentials() throws IOException
    {
        Properties dataBaseProperties = new Properties();

        dataBaseProperties.setProperty("userName", txtUserName.getText().trim());
        dataBaseProperties.setProperty("password", txtPassword.getText().toString().trim());
        dataBaseProperties.setProperty("dbUrl", "jdbc:oracle:thin:@" + txtHost.getText().trim() + ":" + txtPort.getText().trim() + ":XE");
        dataBaseProperties.setProperty("jdbcDriver", "oracle.jdbc.OracleDriver");

        dataBaseProperties.store(new FileOutputStream(new File(databasePropertiesFilePath)), null);
    }

    private void testDatabaseCredentials() throws SQLException
    {
        DatabaseConnection.getInstance();
        PersistenceDbManager.getInstance();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        lblUserName = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        btnHelp = new javax.swing.JButton();
        lblHost = new javax.swing.JLabel();
        Port = new javax.swing.JLabel();
        txtHost = new javax.swing.JTextField();
        txtPort = new javax.swing.JTextField();
        ckbInitDb = new javax.swing.JCheckBox();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        lblUserName.setText("User name");

        lblPassword.setText("Password");

        btnHelp.setText("Help");
        btnHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHelpActionPerformed(evt);
            }
        });

        lblHost.setText("Host");

        Port.setText("Port");

        txtHost.setText("localhost");

        txtPort.setText("1521");

        ckbInitDb.setText("Initialize database");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 150, Short.MAX_VALUE)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnHelp))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblHost)
                            .addComponent(Port)
                            .addComponent(lblPassword)
                            .addComponent(lblUserName))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ckbInitDb)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(txtUserName)
                            .addComponent(txtPassword)
                            .addComponent(txtHost)
                            .addComponent(txtPort))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUserName)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblHost)
                    .addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Port)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ckbInitDb)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton)
                    .addComponent(btnHelp))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(okButton);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        doLogin();
        if (loginSuccess)
        {
            doClose(RET_OK);
        }
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        if (AppUtils.askExitConfirm() == JOptionPane.YES_OPTION)
        {
           doClose(RET_CANCEL);
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void btnHelpActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnHelpActionPerformed
    {//GEN-HEADEREND:event_btnHelpActionPerformed
        String message = "User Name - The login user name defined in the Oracle server. "
                + "\nPassword - The password for the login user. "
                + "\nHost - The host name where Oracle server is running. "
                + "Default is 127.0.0.1 - the IP address of localhost. "
                + "\nPort - The port number where Oracle is listening for connection. Default is 1521. "
                + "\nInitialize database - Database creation and population.";
        JOptionPane.showMessageDialog(rootPane, message, "Login help", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_btnHelpActionPerformed

    private void doClose(int retStatus)
    {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Port;
    private javax.swing.JButton btnHelp;
    private javax.swing.JButton cancelButton;
    private javax.swing.JCheckBox ckbInitDb;
    private javax.swing.JLabel lblHost;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblUserName;
    private javax.swing.JButton okButton;
    private javax.swing.JTextField txtHost;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables
    private int returnStatus = RET_CANCEL;
}
